export default defineNuxtPlugin(() => {
  addRouteMiddleware(
    "auth",
    defineNuxtRouteMiddleware(async (to) => {
      // console.log('路由授权拦截器');

      if (to.meta.auth === false) return;

      const auth = useAuth();
      // let hasPermission = false;
      if (auth.accessToken) {
        // await useAsyncDataNextTick(auth);
        // if (auth.pending) {
        // 正在获取user,等待获取完毕
        // await new Promise((resolve, reject) => {
        //   watchOnce(() => auth.pending, resolve);
        // });
        // }
        await until(toRef(auth, "pending")).toBe(false);

        if (!auth.user) {
          return navigateTo({
            replace: true,
            path: "/login",
            query: {
              callback: to.fullPath,
            },
          });
        }

        // const menu = useMenus();

        // await useAsyncDataNextTick(menu);
        // if (menu.pending) {
        // await new Promise((resolve, reject) => {
        //   watchOnce(() => menu.pending, resolve);
        // });
        // }
        // await until(toRef(menu, 'pending')).toBe(false);

        // const toMenu = menu.getMenuByPath(to.path);

        // if (!toMenu || auth.hasMenu(toMenu.menu.key)) {
        //   // hasPermission = true;
        //   return;
        // }
      } else {
        return navigateTo({
          replace: true,
          path: "/login",
          query: {
            callback: to.fullPath,
          },
        });
      }

      // console.log(hasPermission);

      // if (!hasPermission) {

      // }
    }),
    { global: true }
  );
});
